import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { verifyUserPassword } from '@zeronejs/utils';
import { UserService } from 'src/api/user/user.service';
import { ReqUser } from './index';

@Injectable()
export class AuthService {
    constructor(private usersService: UserService, private jwtService: JwtService) {}

    async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.usersService.findOneByUsername(username);
        const verify = await verifyUserPassword(pass, user.password);
        if (user && verify) {
            Reflect.deleteProperty(user, 'password');
            // const { password, ...result } = user;
            return user;
        }
        return null;
    }
    /**
     * 登录并生成token
     * @param user 完整用户
     * @returns
     */
    async login(user: any) {
        const payload: ReqUser = { username: user.username, _id: user._id };
        return {
            accessToken: this.jwtService.sign(payload),
        };
    }
}
